package cn.aixuegao.service.admin.impl;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.aixuegao.common.config.UploadConfig;
import cn.aixuegao.common.exception.StorageException;
import cn.aixuegao.common.exception.StorageFileNotFoundException;
import cn.aixuegao.service.admin.StorageService;
import org.springframework.core.io.UrlResource;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

@Service
public class StorageServiceImpl implements StorageService{

	/**
	 * 根目录
	 */
	private final Path rootLocation;
	
	@Autowired
	public StorageServiceImpl(UploadConfig uploadConfig) {
		File file = new File(uploadConfig.getPath());
		if(!file.exists()){
			file.mkdir();
		} 
		this.rootLocation = Paths.get(uploadConfig.getPath());
	}

	//存储文件
    @Override
    public String store(MultipartFile file) {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file " + filename);
            }
            if (filename.contains("..")) {
                // This is a security check
                throw new StorageException(
                        "Cannot store file with relative path outside current directory "
                                + filename);
            }
            String storeFileName = String.valueOf(System.currentTimeMillis()) + filename.substring(filename.indexOf("."), filename.length());
            Files.copy(file.getInputStream(), this.rootLocation.resolve(storeFileName),
                    StandardCopyOption.REPLACE_EXISTING);
            return storeFileName;
        } catch (IOException e) {
            throw new StorageException("Failed to store file " + filename, e);
        }
    }

    //加载所有文件的路径
    @Override
    public Stream<Path> loadAll() {
        try {
            return Files.walk(this.rootLocation, 1)
                    .filter(path -> !path.equals(this.rootLocation))
                    .map(path -> this.rootLocation.relativize(path));
        } catch (IOException e) {
            throw new StorageException("Failed to read stored files", e);
        }

    }

    //加载指定文件的路径
    @Override
    public Path load(String filename) {
        return rootLocation.resolve(filename);
    }

    //加载指定文件为资源用于返回客户端
    @Override
    public Resource loadAsResource(String filename) {
        try {
            Path file = load(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new StorageFileNotFoundException(
                        "Could not read file: " + filename);

            }
        } catch (MalformedURLException e) {
            throw new StorageFileNotFoundException("Could not read file: " + filename, e);
        }
    }

    @Override
    public void deleteAll() {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

    @Override
    public void init() {
        try {
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            throw new StorageException("Could not initialize storage", e);
        }
    }

}
